#include "sql_compiler_cpp/Lexer.h"
#include "sql_compiler_cpp/Parser.h"
#include "storage_system_cpp/StorageManager.h"
#include <iostream>
#include <memory>

class DatabaseEngine
{
public:
    DatabaseEngine()
        : storage_manager_(std::make_unique<MiniDB::StorageManager>(20, MiniDB::ReplacementPolicy::LRU))
    {
        std::cout << "🚀 Database Engine initialized" << std::endl;
    }

    ~DatabaseEngine()
    {
        std::cout << "🛑 Database Engine shut down" << std::endl;
    }

    // Get cache stats
    const MiniDB::CacheStats &getCacheStats() const
    {
        return storage_manager_->getCacheStats();
    }

    // Get table names
    std::vector<std::string> getTableNames() const
    {
        return storage_manager_->getTableNames();
    }

    // Print table info
    void printTableInfo(const std::string &table_name) const
    {
        storage_manager_->printTableInfo(table_name);
    }

    // Execute SQL statement
    bool executeSQL(const std::string &sql)
    {
        std::cout << "\n📝 Executing SQL: " << sql << std::endl;

        // 1. Lexical Analysis
        MiniDB::Lexer lexer(sql);
        auto tokens = lexer.tokenize();

        // 2. Syntax Analysis
        MiniDB::Parser parser(tokens);
        auto statements = parser.parse();

        // 3. Execute statements
        for (const auto &stmt : statements)
        {
            if (!executeStatement(stmt))
            {
                return false;
            }
        }

        return true;
    }

private:
    std::unique_ptr<MiniDB::StorageManager> storage_manager_;

    bool executeStatement(std::shared_ptr<MiniDB::Statement> stmt)
    {
        if (auto create_stmt = std::dynamic_pointer_cast<MiniDB::CreateTableStatement>(stmt))
        {
            return executeCreateTable(create_stmt);
        }
        else if (auto insert_stmt = std::dynamic_pointer_cast<MiniDB::InsertStatement>(stmt))
        {
            return executeInsert(insert_stmt);
        }
        else if (auto select_stmt = std::dynamic_pointer_cast<MiniDB::SelectStatement>(stmt))
        {
            return executeSelect(select_stmt);
        }
        else if (auto delete_stmt = std::dynamic_pointer_cast<MiniDB::DeleteStatement>(stmt))
        {
            return executeDelete(delete_stmt);
        }

        std::cerr << "Unsupported statement type" << std::endl;
        return false;
    }

    bool executeCreateTable(std::shared_ptr<MiniDB::CreateTableStatement> stmt)
    {
        std::cout << "  🏗️  Creating table: " << stmt->table_name << std::endl;
        return storage_manager_->createTable(stmt->table_name);
    }

    bool executeInsert(std::shared_ptr<MiniDB::InsertStatement> stmt)
    {
        std::cout << "  ➕ Inserting into table: " << stmt->table_name << std::endl;

        if (stmt->values.empty())
        {
            std::cerr << "No values to insert" << std::endl;
            return false;
        }

        for (size_t i = 0; i < stmt->values.size(); ++i)
        {
            const auto &row = stmt->values[i];
            for (size_t j = 0; j < row.size(); ++j)
            {
                if (auto literal = std::dynamic_pointer_cast<MiniDB::Literal>(row[j]))
                {
                    int id = 0;
                    std::string data;

                    // Extract values from literal
                    if (std::holds_alternative<int>(literal->value))
                    {
                        if (j == 0)
                            id = std::get<int>(literal->value);
                        else
                            data = std::to_string(std::get<int>(literal->value));
                    }
                    else if (std::holds_alternative<std::string>(literal->value))
                    {
                        if (j == 0)
                            id = std::stoi(std::get<std::string>(literal->value));
                        else
                            data = std::get<std::string>(literal->value);
                    }

                    if (j == 0)
                    {
                        MiniDB::Record record(id, data);
                        if (!storage_manager_->insertRecord(stmt->table_name, record))
                        {
                            return false;
                        }
                    }
                }
            }
        }

        return true;
    }

    bool executeSelect(std::shared_ptr<MiniDB::SelectStatement> stmt)
    {
        auto from_clause = std::dynamic_pointer_cast<MiniDB::FromClause>(stmt->from_clause);
        if (!from_clause)
        {
            std::cerr << "Invalid FROM clause" << std::endl;
            return false;
        }

        std::cout << "  🔍 Selecting from table: " << from_clause->table_name << std::endl;

        auto records = storage_manager_->getRecords(from_clause->table_name);

        std::cout << "  📊 Results:" << std::endl;
        for (const auto &record : records)
        {
            if (!record.is_deleted)
            {
                std::cout << "    ID: " << record.id << ", Data: " << record.data << std::endl;
            }
        }

        return true;
    }

    bool executeDelete(std::shared_ptr<MiniDB::DeleteStatement> stmt)
    {
        std::cout << "  🗑️  Deleting from table: " << stmt->table_name << std::endl;

        auto records = storage_manager_->getRecords(stmt->table_name);
        for (const auto &record : records)
        {
            storage_manager_->deleteRecord(stmt->table_name, record.id);
        }

        return true;
    }
};

int main()
{
    std::cout << "🎯 小型数据库系统 - 完整集成测试" << std::endl;
    std::cout << "========================================" << std::endl;

    DatabaseEngine db;

    // Test SQL statements
    std::vector<std::string> test_sqls = {
        "CREATE TABLE users (id INT, name VARCHAR(50));",
        "INSERT INTO users VALUES (1, 'Alice');",
        "INSERT INTO users VALUES (2, 'Bob');",
        "INSERT INTO users VALUES (3, 'Charlie');",
        "SELECT * FROM users;",
        "CREATE TABLE products (id INT, name VARCHAR(50));",
        "INSERT INTO products VALUES (101, 'Laptop');",
        "INSERT INTO products VALUES (102, 'Mouse');",
        "SELECT * FROM products;",
        "DELETE FROM users;" // Simplified delete
    };

    std::cout << "\n🔬 执行测试SQL语句:" << std::endl;
    for (const auto &sql : test_sqls)
    {
        if (!db.executeSQL(sql))
        {
            std::cerr << "❌ SQL执行失败: " << sql << std::endl;
            return 1;
        }
    }

    std::cout << "\n📈 显示系统统计信息:" << std::endl;
    auto stats = db.getCacheStats();
    stats.print();

    std::cout << "\n📋 显示表信息:" << std::endl;
    auto tables = db.getTableNames();
    for (const auto &table : tables)
    {
        db.printTableInfo(table);
    }

    std::cout << "\n==========================================" << std::endl;
    std::cout << "✅ 数据库集成测试完成！" << std::endl;

    return 0;
}
